package cc.telecomdigital.tdstock.trading;

import cc.telecomdigital.tdstock.R;
import cc.telecomdigital.tdstock.Framework.UniqueItem.TDStockLog;
import cc.telecomdigital.tdstock.Services.CommunicTools;
import cc.telecomdigital.tdstock.activity.RealtimeStockActivity;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppBannerDataSet;
import cc.telecomdigital.tdstock.trading.Common.Trade_AppConstant;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockReqOrderItem;
import cc.telecomdigital.tdstock.trading.Common.Trade_StockViewInfoItem;
import cc.telecomdigital.tdstock.trading.Services.TradeAppInfo;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote;
import cc.telecomdigital.tdstock.trading.Services.TradeLogin;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.ITradeGetStockQuoteResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeGetDetailStockQuote.TradeGetStockQuoteResult;
import cc.telecomdigital.tdstock.trading.Services.TradeLogin.ITradeLoginResponse;
import cc.telecomdigital.tdstock.trading.Services.TradeLogin.TradeLoginResult;
import cc.telecomdigital.tdstock.trading.Tools.ViewCtrlHelper;
import cc.telecomdigital.tdstock.trading.widget.AppDialogOK;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

public class Trade_LoginActivity extends Trade_TemplateActivity implements
	Button.OnClickListener
{
	private int		advRotateId	= -1;
	private int		advMax;

	// Top and Bottom is for testing only, we would not have the enough space
	// to do so

	private ImageView	bottomBanner	= null;
	
	@Override
	public void onCreate(Bundle iSaveInstance)
	{		
		super.onCreate(iSaveInstance);
		
		advMax = Trade_AppBannerDataSet.GetAdvCount(getApplicationContext());
		advRotateId = TradeAppInfo.GetAppPreference().getInt(
				Trade_AppConstant.advIndexPref, 0);
		// Validation Check
		if (advRotateId > advMax)
			advRotateId = advMax;

		// Check Resolution of display
		if ((fScrWidthPixel < Trade_AppConstant.designschemeWidth)
				&& (fScrHeightPixel < Trade_AppConstant.designschemeWidth))
		{
			// Create Dialog box and will be quit
			CreateResolutionErrorPrompt();
			return;
		}

		setContentView(R.layout.trading_login);

		//Add Protective Code
		if (TradeAppInfo.IsAllowDemoOnly(appHost.GetLSClient_ServicePlan()))
			TradeAppInfo.SetAsDemoAccount(true);
		
		// Get the width of the logo Image and use it as a reference to
		// set the width of the other component
		int widthPixel;
		Drawable drawableObj;

		widthPixel = 0;
		try
		{
			//Just pick one of the logo dimension to set the width for the edit box
			drawableObj = getResources().getDrawable(
					R.drawable.img_company_logo);
			widthPixel = drawableObj.getIntrinsicWidth();
		}
		catch (Exception iE)
		{
			iE.printStackTrace();
		}

		// Retrieve saved info if possible
		String loginName, loginPassword;

		if (TradeAppInfo.IsDemoAccount())
		{
			loginName = getString(R.string.demoAccountText);
			loginPassword = "demopassword";
			ViewCtrlHelper.SetEnableRequestView(this, R.id.login_LoginEditText, false);
			ViewCtrlHelper.SetEnableRequestView(this, R.id.login_LoginClearBut, false);		
		}
		else
		{
			//Get the name in a difference way
			SharedPreferences pref;
			
			pref = TradeAppInfo.GetAppPreference();
			loginName = pref.getString(Trade_AppConstant.userNamePref, "");
			if (loginName.equals("") == false)				
				loginName =  TradeAppInfo.DecryptString(loginName);
			
			loginPassword = "";
		}
		
		int extraSize;
		// Get Width for the Option image
		drawableObj = getResources().getDrawable(R.drawable.ic_menu_delete);
		extraSize = drawableObj.getIntrinsicWidth() + 16;

		// Adjust the Edit Box Width
		EditText editTextObj;

		editTextObj = (EditText) findViewById(R.id.login_LoginEditText);
		// Fail safe case
		if (widthPixel != 0)
			editTextObj.setWidth(widthPixel - extraSize);
		if (loginName != "")
			editTextObj.setText(loginName);

		editTextObj = (EditText) findViewById(R.id.login_PasswordEditText);

		// Set max character
		InputFilter[] FilterArray;

		FilterArray = new InputFilter[1];
		FilterArray[0] = new InputFilter.LengthFilter(Trade_AppConstant.maxPasswordLength);
		editTextObj.setFilters(FilterArray);

		// Fail safe case
		if (widthPixel != 0)
			editTextObj.setWidth(widthPixel - extraSize);

		editTextObj.setText(loginPassword);

		// Add text to the check box
		String tmpString;

		ImageButton loginButton;

		// Login Button
		loginButton = (ImageButton) findViewById(R.id.login_LoginButton);
		loginButton.setOnClickListener(this);

		TextView textViewObj;

//		// Prompt Message, the company link that will bring to the browser
//		textViewObj = (TextView) findViewById(R.id.login_RegisterLinkText);
//		if (widthPixel != 0)
//			textViewObj.setWidth(widthPixel);
//		textViewObj.setMovementMethod(LinkMovementMethod.getInstance());

		// Copyright
		textViewObj = (TextView) findViewById(R.id.login_CopyrightLabel);
		if (widthPixel != 0)
			textViewObj.setWidth(widthPixel);

		// Version Label
		textViewObj = (TextView) findViewById(R.id.login_VersionLabel);
		if (TradeAppInfo.IsDemoAccount())
			tmpString = getString(R.string.demoText) + " "
					+ getString(R.string.versionText) + ": ";
		else
			tmpString = getString(R.string.versionText) + ": ";

		String versionName;

		try
		{
			versionName = TradeAppInfo.GetProgramVersion();
			if (TradeAppInfo.IsDevelopment())
				versionName += "_Dev";
		}
		catch (Exception iE)
		{
			iE.printStackTrace();
			versionName = "---";
		}

		textViewObj.setText(tmpString + versionName + "  ");

		findViewById(R.id.login_LoginClearBut).setOnClickListener(this);
		findViewById(R.id.login_PasswordClearBut).setOnClickListener(this);
		findViewById(R.id.login_LoginEditText).setOnFocusChangeListener(
				_keyboardPopListener);
		findViewById(R.id.login_PasswordEditText).setOnFocusChangeListener(
				_keyboardPopListener);
		
		((EditText) findViewById(R.id.login_PasswordEditText))
				.setOnEditorActionListener(new TextView.OnEditorActionListener()
				{
					@Override
					public boolean onEditorAction(TextView v,
							int actionId, KeyEvent event)
					{
						if (actionId == EditorInfo.IME_ACTION_DONE)
						{
							findViewById(R.id.login_LoginButton).performClick();
							return true;
						}
						return false;
					}
				});
		
		View viewObj;
		
		viewObj = findViewById(R.id.trade_login_demobutton);
		if (TradeAppInfo.IsDemoAccount())
		{
			((ImageView)findViewById(R.id.trading_login_logo)).setBackgroundResource(R.drawable.img_demo_company_logo);
			viewObj.setVisibility(View.INVISIBLE);
			// Make the adv type available
			try
			{
				bottomBanner = (ImageView) findViewById(R.id.view_bottomadvbanner_Image);
				bottomBanner.setVisibility(View.VISIBLE);
			}
			catch (Exception ex)
			{
				ex.getStackTrace();
			}
			StartDemoLogon();
		}
		else
		{
			((ImageView)findViewById(R.id.trading_login_logo)).setBackgroundResource(R.drawable.img_company_logo);			
			viewObj.setOnClickListener(this);
		}
		
		findViewById(R.id.trade_login_back).setOnClickListener(this);	
	}

	@Override
	public void onResume()
	{
		super.onResume();
		UpdateAdvBanner();
	}
	
	@Override
	public void onPause()
	{
		StopDemoLogon();
		super.onPause();
	}
	
	private Handler  handler       = null;
	private Runnable demoAutoLogon = null; 
	public void StartDemoLogon()
	{
		if (TradeAppInfo.IsDemoAccount() == false)
			return;
		
		if (handler == null)
			handler = new Handler();
		
		if (demoAutoLogon == null)
		{
			demoAutoLogon = new Runnable()
			{
				public void run()
				{
					findViewById(R.id.login_LoginButton).performClick();
				}
			};
		}			
		
		handler.removeCallbacks(demoAutoLogon);
		handler.postDelayed(demoAutoLogon, 5000);		
	}
	
	public void StopDemoLogon()
	{
		if ((handler != null) && (demoAutoLogon != null))
			handler.removeCallbacks(demoAutoLogon);		
	}
	
	protected void UpdateAdvBanner()
	{
		// Each creation will rotate an id
		if (++advRotateId >= advMax)
			advRotateId = 0;

		if (bottomBanner != null)
		{
			try
			{
				int  nextAppId = Trade_AppBannerDataSet.GetImageResource(advRotateId);
				bottomBanner.setImageResource(nextAppId);	
				Animation animatAction = AnimationUtils.loadAnimation(
						this,
						Trade_AppBannerDataSet.BANNER_ANIMATE_TYPE);
				animatAction
						.setDuration(Trade_AppBannerDataSet.BANNER_ANIMATE_CONSTANT);
				bottomBanner.startAnimation(animatAction);				
				
				
//				Bitmap nextApp;
//
//				nextApp = Trade_AppBannerDataSet.GetAdvBitmapFromResource(
//						getApplicationContext(), advRotateId);
//							
//				if (nextApp != null)
//				{
//					bottomBanner.setImageBitmap(nextApp);
//										
//					Animation animatAction = AnimationUtils.loadAnimation(
//							this,
//							Trade_AppBannerDataSet.BANNER_ANIMATE_TYPE);
//					animatAction
//							.setDuration(Trade_AppBannerDataSet.BANNER_ANIMATE_CONSTANT);
//					bottomBanner.startAnimation(animatAction);
//				}
			}
			catch (Exception iE)
			{
			}
		}
		// Update the index
		if (bottomBanner != null)
			TradeAppInfo.GetAppPreference().edit()
					.putInt(Trade_AppConstant.advIndexPref, advRotateId)
					.commit();
	}

	private void CreateResolutionErrorPrompt()
	{
		AppDialogOK resolutionPrompt;

		resolutionPrompt = new AppDialogOK(this);
		// Do the request before setting the view
		resolutionPrompt.SetTextContent(R.string.displayResError);
		resolutionPrompt.show(new AppDialogOK.IAppDialogOK()
		{
			@Override
			public void OnDialogCancel(DialogInterface iDialog)
			{
				SafeApplicationExit();
			}

			@Override
			public void OnOK_Click(DialogInterface iDialog)
			{
				SafeApplicationExit();
			}
		}, true);
	}

	@Override
	public void onClick(View iViewObj)
	{
		switch (iViewObj.getId())
		{
			case R.id.login_LoginClearBut:
				((EditText) findViewById(R.id.login_LoginEditText))
						.setText("");
				break;

			case R.id.login_PasswordClearBut:
				((EditText) findViewById(R.id.login_PasswordEditText))
						.setText("");
				break;

			case R.id.login_LoginButton:
				// Try to login to server
				// If successfully login and have the preference
				{
					EditText editBoxObj;
					String loginName, loginPasswd;
	
					//Flush the auto login that we have
					StopDemoLogon();
					
					if (isLogonProcessStart)
						return;
										
					editBoxObj = (EditText) findViewById(R.id.login_LoginEditText);
					loginName = editBoxObj.getText().toString();
					/* trim front and back space for login */
					loginName = loginName.trim();
	
					editBoxObj = (EditText) findViewById(R.id.login_PasswordEditText);
					loginPasswd = editBoxObj.getText().toString();
	
					if (!CommunicTools.isASCIIString(loginName) && !TradeAppInfo.IsDemoAccount())					
					{
						Animation animatAction = AnimationUtils
								.loadAnimation(
										this,
										Trade_AppConstant.EDITBOX_ERROR_ANIMATE_TYPE);
						animatAction
								.setDuration(Trade_AppConstant.EDITBOX_ERROR_ANIMATE_TIME);
						findViewById(R.id.login_LoginEditText).startAnimation(
								animatAction);
						findViewById(R.id.login_LoginEditText).requestFocus();					
						break;
					}
	
					if (CommunicTools.isASCIIString(loginPasswd) == false)					
					{
						Animation animatAction = AnimationUtils
								.loadAnimation(
										this,
										Trade_AppConstant.EDITBOX_ERROR_ANIMATE_TYPE);
						animatAction
								.setDuration(Trade_AppConstant.EDITBOX_ERROR_ANIMATE_TIME);
						findViewById(R.id.login_PasswordEditText)
								.startAnimation(animatAction);
						findViewById(R.id.login_PasswordEditText)
								.requestFocus();				
						break;
					}
					HideKeyBoard();
		
					// Now try the connection, maybe we should do this in a
					// thread
					LoginProcessStart();
				}
				break;
			case R.id.trade_login_demobutton:
				{
					EditText  editTextObj;
					
					if (TradeAppInfo.IsDemoAccount())
						break;
					
					((ImageView)findViewById(R.id.trading_login_logo)).setBackgroundResource(R.drawable.img_demo_company_logo);	
					//Disable the clear button
					ViewCtrlHelper.SetEnableRequestView(this, R.id.login_LoginClearBut, false);					
					editTextObj = (EditText)findViewById(R.id.login_LoginEditText);
					editTextObj.setEnabled(false);
					editTextObj.setFocusable(false);					
					editTextObj.setText(R.string.demoAccountText);
					
					editTextObj = (EditText)findViewById(R.id.login_PasswordEditText);					
					editTextObj.setText("demopassword");	
					
					HideKeyBoard();
					
					TradeAppInfo.SetAsDemoAccount(true);	
					//Set the button disable
					iViewObj.setVisibility(View.INVISIBLE);	

					try
					{
						bottomBanner = (ImageView) findViewById(R.id.view_bottomadvbanner_Image);
						bottomBanner.setVisibility(View.VISIBLE);
						UpdateAdvBanner();
					}
					catch (Exception ex)
					{
						ex.getStackTrace();
					}
					StartDemoLogon();
				}
				break;
				
			case R.id.trade_login_back:
				onBackPressed();
				break;
				
				
		}
	}

	@Override
	public void onBackPressed()
	{		
		if (debugMode)
			TDStockLog.i(GetIdentity(), "Overrideing ** Activity onBackPressed");
		
		Class<? extends Activity>  sourceFrom;
		
		sourceFrom = TradeAppInfo.GetPrimaryEntryClass();
		if (sourceFrom == null)
			SwitchFreeActivity(RealtimeStockActivity.class);
		else
			SwitchFreeActivity(sourceFrom);		
	}
	
	private static final int	CLEAR_LOGIN		= 1;
//	private static final int	SHOW_DISCLAIMER	= 2;

	// Create Menu when pressing the hard menu button below
	@Override
	public boolean onCreateOptionsMenu(Menu iMenu)
	{
		super.onCreateOptionsMenu(iMenu);
		// Add the menu Item to the menu
		MenuItem menuItemObj;

//		menuItemObj = iMenu.add(0, SHOW_DISCLAIMER, Menu.NONE,
//				R.string.disclaimerText);
//		menuItemObj.setIcon(R.drawable.ic_menu_lightbulb);
//		menuItemObj.setShortcut('0', 'd');

		menuItemObj = iMenu.add(0, CLEAR_LOGIN, Menu.NONE,
				R.string.resetLogin);
		menuItemObj.setIcon(R.drawable.ic_menu_edit);
		menuItemObj.setShortcut('0', 'c');

		return true;
	}

	// Selection from Menu menu
	@Override
	public boolean onOptionsItemSelected(MenuItem iMenu)
	{
		super.onOptionsItemSelected(iMenu);
		switch (iMenu.getItemId())
		{
//			case SHOW_DISCLAIMER:
//				ShowPromptMessage(getString(R.string.disclaimerContentText));
//				return true;
				
			case CLEAR_LOGIN:
				if (TradeAppInfo.IsDemoAccount() == false)
				{
					SharedPreferences.Editor pref;
					pref = TradeAppInfo.GetAppPreference().edit();
					
					pref.remove(Trade_AppConstant.userNamePref);
					((EditText) findViewById(R.id.login_LoginEditText))
							.setText("");
					pref.commit();						
				}
				((EditText) findViewById(R.id.login_PasswordEditText))
						.setText("");
//				SetUserPassword("");				
				// Clear the cert
//				TradeAppInfo.FlushClientCertIfExist(this);
				return true;
		}
		return false;
	}

	private void SafeApplicationExit()
	{
		// Kill Yourself for sure
		appHost.Dismiss();
	}

	private void LoginProcessStart()
	{
		if (TradeAppInfo.IsDemoAccount())
		{
			ShowWaitingDialog();			
			RequestToLoginProcess();
			return;
		}
		
		if (IsNetworkAvailable() == false)
		{
			ShowPromptMessage(getString(R.string.commErrorText));
			return;
		}

		ShowWaitingDialog();
		RequestToLoginProcess();
		
//		// If No security need then we can request directly
//		if (!TradeAppInfo.useSSLSetting)
//		{
//			RequestToLoginProcess();
//			return;
//		}
//
//		// If the SSL file exist then we login directly
//		if (TradeAppInfo.IsClientCerticateExist(this))
//		{
//			RequestToLoginProcess();
//			return;
//		}
//
//		GetClientCertificateProcess();
	}

//	private void GetClientCertificateProcess()
//	{
//		TradeGetClientCert getCertRequest;
//
//		getCertRequest = new TradeGetClientCert(this);
//		getCertRequest.SendRequest(new ITradeGetClientCertResponse()
//		{
//			@Override
//			public void ResponseFunc(boolean iSuccessfulSend)
//			{
//				if (iSuccessfulSend)
//				{
//					RequestToLoginProcess();
//					return;
//				}
//				DismissWaitingDialog();
//				ShowInfoBox(getString(R.string.systemInfoText),
//						getString(R.string.commErrorText));
//			}
//		});
//	}

	private boolean isLogonProcessStart = false;
	private void RequestToLoginProcess()
	{
		final TradeLogin loginRequest;
		EditText editBoxObj;
		String loginName, loginPasswd;

		isLogonProcessStart = true;
		
		editBoxObj = (EditText) findViewById(R.id.login_LoginEditText);
		loginName = editBoxObj.getText().toString();
		/* Front and back trim spacing */
		loginName = loginName.trim();

		editBoxObj = (EditText) findViewById(R.id.login_PasswordEditText);
		loginPasswd = editBoxObj.getText().toString();

		loginRequest = new TradeLogin(this, loginName, loginPasswd);
		loginRequest.SendRequest(TradeAppInfo.IsDemoAccount(),
				new ITradeLoginResponse()
				{
					@Override
					public void ResponseFunc(boolean iSuccessfulSend,
							TradeLoginResult iResponse)
					{
						isLogonProcessStart = false;						
						if (!iSuccessfulSend)
						{
							DismissWaitingDialog();
							ShowPromptMessage(getString(R.string.commErrorText));
							return;
						}

						if ((iResponse.StatusCode != null) && iResponse.StatusCode.equals("1"))
						{
							SaveLoginPreference();
							DismissWaitingDialog();
							if ((iResponse.BrokerMessage == null)
									|| (iResponse.BrokerMessage
											.length() == 0))
							{
								PerformWhenLogonSuccess();
								return;
							}
							CreateSuccessLoginMsgBox(iResponse.BrokerMessage);
							return;
						}
						DismissWaitingDialog();
						loginRequest.Dispose();
						CreateFailLoginMsgBox(iResponse.BrokerMessage);
					}
				});
	}

	private void PerformWhenLogonSuccess()
	{	
		//Run as the normal
		if (TradeAppInfo.TradeKeySwap_Ready == false)
		{
			//Flush the save data
			TradeAppInfo.SetStockViewInfoItem(null);				
			SwitchForwardActivity(Trade_tradingOptionActivity.class);	
			return;
		}
		
		Trade_StockViewInfoItem viewStockInfo;
		String                  tradeOrder;
			
		tradeOrder    = TradeAppInfo.GetStockViewPrepareAction();
		viewStockInfo = TradeAppInfo.GetStockViewInfoItem();
		if ((viewStockInfo == null) || !TradeAppInfo.TradeKeySwap_Ready)
		{
			//Flush the save data
			TradeAppInfo.SetStockViewInfoItem(null);			
			SwitchForwardActivity(Trade_tradingOptionActivity.class);
			return;
		}
		
		//Flush the save data
		TradeAppInfo.SetStockViewInfoItem(null);

		if (TradeAppInfo.IsDemoAccount())
		{
            // When an OK is pressed, we will start the keypad with available
            // information
			String priceString;					
			Trade_StockReqOrderItem transferObj;
			Intent 	intentObj;

			intentObj = new Intent(actContext, Trade_OrderKeypadActivity.class);
			/* Change to the dummy data */
			viewStockInfo = new Trade_StockViewInfoItem( viewStockInfo.stockCode, 
					 "示範", "Demo");					
			viewStockInfo.SetStartPrice("868.5", false);
			viewStockInfo.SetPriceInfo("883.5", "883.0", "883.5", true);
			viewStockInfo.SetStepVolume("400");
			viewStockInfo.SetSpreadPrice("0.5");
			viewStockInfo.SetCurrencyCode("HKD");

			transferObj = new Trade_StockReqOrderItem( "1234", viewStockInfo.stockCode,
											   viewStockInfo.chnName, viewStockInfo.engName);
			// The outstanding is the remaining quantity for order
			transferObj.SetOrderQuantity("0", "0", "400");
			transferObj.SetOrderType("E");
			// Assume it is a buy
			
			priceString = viewStockInfo.GetCurAskPriceText();
			if (tradeOrder.equals(Trade_StockReqOrderItem.TRANSACTIONTYPE_ASK))
				priceString = viewStockInfo.GetCurBidPriceText();
			
			transferObj.SetOrderSide(tradeOrder);
			transferObj.SetOrderPrice(priceString);	
			// Use previous price for setting
			transferObj.SetCurrencyCode(viewStockInfo.currencyCode);		

			//Place the Order info, then the Stock View Info
			intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo, transferObj);
			intentObj.putExtra(Trade_AppConstant.stockViewInfo, viewStockInfo);
						
			// Place the bundle object to the intent
			SwitchForwardActivity(Trade_OrderKeypadActivity.class, intentObj);
			return;
		}
		
		if (TradeAppInfo.IsBMPMode())
		{
			if (!IsNetworkAvailable())
			{
				SwitchForwardActivity(Trade_tradingOptionActivity.class);
				return;
			}
			
			final TradeGetDetailStockQuote quoteRequest;
			final String                   iiTradeOrder;
			
			iiTradeOrder = tradeOrder;
			ShowWaitingDialog();
			quoteRequest = new TradeGetDetailStockQuote( actContext);
			quoteRequest.SetRequestQuoteInfo( appHost.IsDevelopment(), viewStockInfo.stockCode, 
										      appHost.GetLSClient_AccountLogonName(), appHost.GetLSClient_SessionKey());
			quoteRequest.SendRequest( TradeAppInfo.IsDemoAccount(),
					new ITradeGetStockQuoteResponse()
					{
						@Override
						public void ResponseFunc( boolean iSuccessfulSend, TradeGetStockQuoteResult iResponse)
						{					
							quoteRequest.Dispose();
							DismissWaitingDialog();
							if (iSuccessfulSend == false)
							{
								AppDialogOK msgBox;

								msgBox = new AppDialogOK(actContext);
								msgBox.SetTextContent(R.string.commErrorText);
								msgBox.SetButtonText(R.string.okText);
								msgBox.show(new AppDialogOK.IAppDialogOK()
								{
									@Override
									public void OnOK_Click(DialogInterface iDialog)
									{
										SwitchForwardActivity(Trade_tradingOptionActivity.class);
									}

									@Override
									public void OnDialogCancel(DialogInterface iDialog)
									{
										SwitchForwardActivity(Trade_tradingOptionActivity.class);
									}
								}, true);
																
								return;
							}
	
							if (!iResponse.resultCode.equals("0"))
							{
								String textValue;
								
								textValue = iResponse.errorMessage;
								if (textValue.equals(""))
									textValue = getString(R.string.commErrorText);

								if (iResponse.resultCode.equals("-1"))
									appHost.LS_Client_ResetConnection();
								
								AppDialogOK msgBox;

								msgBox = new AppDialogOK(actContext);
								msgBox.SetTextContent(textValue);
								msgBox.SetButtonText(R.string.okText);
								msgBox.show(new AppDialogOK.IAppDialogOK()
								{
									@Override
									public void OnOK_Click(DialogInterface iDialog)
									{
										SwitchForwardActivity(Trade_tradingOptionActivity.class);
									}

									@Override
									public void OnDialogCancel(DialogInterface iDialog)
									{
										SwitchForwardActivity(Trade_tradingOptionActivity.class);
									}
								}, true);
																
								return;
							}
							PlaceSwitchTradeOrderKeyPad(iResponse.stockQuoteItem, iiTradeOrder);								
							return;
						}
					});
			return;
		}		
		PlaceSwitchTradeOrderKeyPad(viewStockInfo, tradeOrder);				
	}
	
	private void PlaceSwitchTradeOrderKeyPad(Trade_StockViewInfoItem iStockInfo, String iOrderSide)
    {
		String priceString;					
		Trade_StockReqOrderItem transferObj;
		Intent 	intentObj;
		
		intentObj = new Intent(actContext, Trade_OrderKeypadActivity.class);			
		// Provide with no order no
		transferObj = new Trade_StockReqOrderItem("",
		iStockInfo.stockCode, iStockInfo.chnName,
		iStockInfo.engName);
		// The outstanding is the remaining quantity for order
		transferObj.SetOrderQuantity("0", "0", iStockInfo.stepVolume);			
		
		transferObj.SetOrderType("E");
		// Assume it is a buy
		
		priceString = iStockInfo.GetCurAskPriceText();
		if (iOrderSide.equals(Trade_StockReqOrderItem.TRANSACTIONTYPE_ASK))
			priceString = iStockInfo.GetCurBidPriceText();
		
		transferObj.SetOrderSide(iOrderSide);
		transferObj.SetOrderPrice(priceString);	
		// Use previous price for setting
		transferObj.SetCurrencyCode(iStockInfo.currencyCode);		

		//Place the Order info, then the Stock View Info
		intentObj.putExtra(Trade_AppConstant.stockOrderRequestInfo, transferObj);
		intentObj.putExtra(Trade_AppConstant.stockViewInfo, iStockInfo);
		
		// Place the bundle object to the intent
		SwitchForwardActivity(Trade_OrderKeypadActivity.class, intentObj);		
	}
	
	private void CreateSuccessLoginMsgBox(String iContent)
	{
		AppDialogOK afterLoginMsgBox;

		afterLoginMsgBox = new AppDialogOK(this);
		afterLoginMsgBox.SetTextContent(iContent);
		afterLoginMsgBox.SetButtonText(R.string.okText);

		afterLoginMsgBox.show(new AppDialogOK.IAppDialogOK()
		{
			@Override
			public void OnOK_Click(DialogInterface iDialog)
			{
				PerformWhenLogonSuccess();
			}

			@Override
			public void OnDialogCancel(DialogInterface iDialog)
			{
				PerformWhenLogonSuccess();
			}
		}, true);
	}

	private void CreateFailLoginMsgBox(String iContent)
	{
		AppDialogOK afterLoginMsgBox;

		afterLoginMsgBox = new AppDialogOK(this);
		afterLoginMsgBox.SetTextContent(iContent);
		afterLoginMsgBox.SetButtonText(R.string.okText);
		afterLoginMsgBox.show(null, true);
	}

	// Try to save the preference
	private void SaveLoginPreference()
	{
		String loginName;
		
		loginName = ((EditText) findViewById(R.id.login_LoginEditText))
				.getText().toString();
		loginName = loginName.trim();
		
		TradeAppInfo.SetTradingRegistration(true);		
		TradeAppInfo.SetUserName(loginName);

	}
	
	private AppDialogOK promptMessage = null;
	private void ShowPromptMessage(String iContent)
	{
		if (promptMessage != null)
			promptMessage.dismiss();
		
		promptMessage = ShowInfoBox(iContent);
	}	
}
